//
//  WmcRecentProjectsVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/14.
//

import Photos
import UIKit
import YPBedrock

// MARK: - 扩展WmcSystemAlbumVC + WmcNavigatorProtocol

extension WmcSystemAlbumVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.systemAlbum]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vc = WmcSystemAlbumVC()
        return vc
    }
}

// MARK: - 扩展WmcSystemAlbumVC + WmcVMProtocol

extension WmcSystemAlbumVC: WmcVMProtocol {
    typealias VMType = WmcSystemAlbumVM
}

// MARK: - 扩展WmcSystemAlbumVC + WmcAlbumTransitionProtocol

extension WmcSystemAlbumVC: WmcAlbumTransitionProtocol {}

// MARK: - [WmcSystemAlbumVC]

class WmcSystemAlbumVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.loadAlbumList()

        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus == .limited {
            changeAuthorizationView.isHidden = false
            changeAuthorizationView.snp.updateConstraints { make in
                make.height.equalTo(40)
            }
        }
    }

    // Internal

    /// 选择项目
    lazy var selectProjectsView: WmcSystemAlbumSelectProjectsView = {
        let view = WmcSystemAlbumSelectProjectsView()
        view.isHidden = true
        return view
    }()

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout.YP
            .CreateGridLayout(scrollDirection: .vertical,
                              minimumLineSpacing: 8,
                              minimumInteritemSpacing: 8,
                              sectionInset: Wmc_standardEdge)
        return layout
    }()

    /// 列表显示
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView.YP.Create(layout: layout, delegate: self, dataSource: self, registers: [
            YPRegister(WmcSystemAlbumCell.self),
        ])
        return collectionView
    }()

    /// 收起显示、修改授权提醒视图
    lazy var changeAuthorizationView: WmcSystemAlbumChangeAuthorizationView = {
        let view = WmcSystemAlbumChangeAuthorizationView()
        view.isHidden = true
        return view
    }()

    /// 项目选择按钮
    lazy var albumProjectsSelectBtn: WmcLeftTextRightImgBtn = {
        let btn = WmcLeftTextRightImgBtn()
        btn.font = 22.yp.uiFont(weight: .medium)
        btn.textColor = .wmc_grayH2_323233
        btn.title = "最近项目"
        btn.imageView.image = "arrow_bottom".wmc_image.yp.set(tintColor: UIColor.wmc_mainTheme)
        btn.imgTextSpacing = 8
        btn.isSelected = false
        btn.label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        btn.imageView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
        return btn
    }()

    override func backAction() {
        popVC(style: .bottom)
    }

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "返回"
        navView.backControlWidth = Wmc_screenWidth / 4

        navView.addSubview(albumProjectsSelectBtn)
        albumProjectsSelectBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(navView.backImageView.snp.centerY)
            make.width.lessThanOrEqualToSuperview().multipliedBy(0.5)
        }

        addSubview(changeAuthorizationView)
        changeAuthorizationView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
        }

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(changeAuthorizationView.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }

        addSubview(selectProjectsView)
        selectProjectsView.snp.remakeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
    }

    override func bindViewAction() {
        // 点击项目选择
        albumProjectsSelectBtn.yp.addEvent { [weak self] sender in
            guard let weakSelf = self else { return }
            YPDevice.PlayShake(.light)
            if weakSelf.selectProjectsView.albumListRelay.value.count <= 0 {
                WmcHudManager.toast("暂无相册")
            } else {
                weakSelf.showSelectProjectView(!sender.isSelected)
            }
        }
        // 点击项目选择列表背景的回调
        selectProjectsView.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.showSelectProjectView(false)
        }
        // 点击项目选择列表的回调
        selectProjectsView.didSelectBlock = { [weak self] idx, album in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.selectAlbum(album)
        }
        // 权限修改
        changeAuthorizationView.changeAuthorizationBtn.yp.addEvent { _ in
            WmcAuthorizedManager.showPrivacyAlert(type: .photoAlbum, isHint: false)
        }
    }

    override func bindViewModel() {
        // 将数据绑定到相簿选择视图上
        viewModel.albumListRelay.subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.selectProjectsView.albumListRelay.accept(list)
            if let currentAlbum = weakSelf.viewModel.currentAlbumRelay.value {
                weakSelf.viewModel.selectAlbum(currentAlbum) // 选中当前
            } else if let firstAlbum = list.first {
                // 如果没有数据，则默认加载第一个相册
                weakSelf.viewModel.selectAlbum(firstAlbum) // 选中第一个
            }
        }).disposed(by: rx.disposeBag)

        // 相册名称显示
        viewModel.currentAlbumRelay.subscribe(onNext: { [weak self] album in
            guard let weakSelf = self else { return }
            // 修改标题
            weakSelf.albumProjectsSelectBtn.title = album?.name
        }).disposed(by: rx.disposeBag)

        // 相册内容列表数据信号
        viewModel.albumPhotosRelay.subscribe(onNext: { [weak self] assetList in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            // 滑到头
            weakSelf.collectionView.setContentOffset(.zero, animated: true)
            // 隐藏选择器
            weakSelf.showSelectProjectView(false)
        }).disposed(by: rx.disposeBag)
    }

    /// 显示相簿选择
    func showSelectProjectView(_ show: Bool) {
        albumProjectsSelectBtn.isSelected = show
        albumProjectsSelectBtn.isUserInteractionEnabled = false
        // 箭头动画
        Wmc_SpringAnimation { [weak self] in
            guard let weakSelf = self else { return }
            if show {
                weakSelf.albumProjectsSelectBtn.imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
            } else {
                weakSelf.albumProjectsSelectBtn.imageView.transform = CGAffineTransform(rotationAngle: 0)
            }
        } completion: {}

        // 视图动画
        if show {
            selectProjectsView.isHidden = false
            selectProjectsView.alpha = 0
            UIView.animate(withDuration: Wmc_animationDuration) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.selectProjectsView.alpha = 1
            } completion: { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.albumProjectsSelectBtn.isUserInteractionEnabled = true
            }
        } else {
            selectProjectsView.isHidden = false
            selectProjectsView.alpha = 1
            UIView.animate(withDuration: Wmc_animationDuration) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.selectProjectsView.alpha = 0
            } completion: { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.selectProjectsView.isHidden = true
                weakSelf.albumProjectsSelectBtn.isUserInteractionEnabled = true
            }
        }
        selectProjectsView.showSelectView(show)
    }
}

// MARK: - UICollectionViewDelegate

extension WmcSystemAlbumVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath),
              let asset = viewModel.albumPhotosRelay.value.yp.object(at: indexPath.row) else { return }
        // 获取原图
        WmcAlbumManager.asyncLoadImage(asset: asset,
                                       photoSize: PHImageManagerMaximumSize,
                                       squareCenterMode: false) { [weak self] image in
            guard let weakSelf = self else { return }
            // 使用转场动画
            let y = Self.NavHeight
            let height = Wmc_screenHeight - (y + WmcEditPhotoVC.TooBarHeight)
            let endFrame = CGRect(x: 0, y: y,
                                  width: weakSelf.view.frame.width, height: height)
            weakSelf.transitionAnimation(startView: cell, image: image, endFrame: endFrame) {
                let vm = WmcEditPhotoVM()
                vm.inputImage = image
                // 监听，当图片处理完成后的回调
                vm.saveSubject.subscribe(onNext: { [weak self] image in
                    guard let weakSelf = self else { return }
                    weakSelf.viewModel.loadAlbumList()
                }).disposed(by: weakSelf.rx.disposeBag)
                WmcNavigatorManager.push(.editPhoto, style: .alpha, parms: vm)
            }
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcSystemAlbumVC: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let lineCount: CGFloat = 3
        let lineSpacing = self.layout.minimumLineSpacing * (lineCount - 1)
        let horizontalEdge = self.layout.sectionInset.yp.horizontal
        let width = (collectionView.frame.size.width - lineSpacing - horizontalEdge) / lineCount - 1
        let height = width
        return CGSize(width: width, height: height)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcSystemAlbumVC: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.albumPhotosRelay.value.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcSystemAlbumCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let asset = viewModel.albumPhotosRelay.value.yp.object(at: indexPath.row) {
            cell.configAsset(asset)
        }
        return cell
    }
}
